<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="菜单名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><template #icon><i-ep-search /></template>搜索</el-button
          >
          <el-button @click="resetQuery">
            <template #icon><i-ep-refresh /></template>
            重置</el-button
          >
          <el-button @click="reloadMenu">
            <template #icon><i-ep-refresh-left /></template>
            重新加载菜单</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['sys:menu:add']"
          type="success"
          @click="openDialog('0')"
        >
          <template #icon><i-ep-plus /></template>
          新增</el-button
        >
      </template>

      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="menuList"
        default-expand-all
        highlight-current-row
        row-key="id"
        :expand-row-keys="['1']"
        @row-click="onRowClick"
        class="fix-item"
        style="--fix-top-height: 175px"
        :tree-props="treeProps"
      >
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            <svg-icon :icon-class="scope.row.data.icon" />
            {{ scope.row.data.name }}
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" width="150">
          <template #default="scope">
            <el-tag
              v-if="scope.row.data.type === MenuTypeEnum.CATALOG"
              type="warning"
              >目录</el-tag
            >
            <el-tag
              v-if="scope.row.data.type === MenuTypeEnum.MENU"
              type="success"
              >菜单</el-tag
            >
            <el-tag
              v-if="scope.row.data.type === MenuTypeEnum.BUTTON"
              type="danger"
              >按钮</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column
          label="路由路径"
          align="left"
          min-width="200"
          prop="data.path"
        />

        <el-table-column
          label="组件路径"
          align="left"
          min-width="200"
          prop="data.component"
          show-overflow-tooltip
        />

        <el-table-column
          label="权限标识"
          align="left"
          width="160"
          prop="data.code"
          show-overflow-tooltip
        />

        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="!scope.row.data.hidden" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" align="center" label="操作" width="250">
          <template #default="scope">
            <el-button
              v-if="scope.row.data.type == '0' || scope.row.data.type == '1'"
              v-hasPerm="['sys:menu:add']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.data.code)"
            >
              <i-ep-plus />新增
            </el-button>

            <el-button
              v-if="scope.row.data.type == '1'"
              v-hasPerm="['sys:menu:add']"
              type="primary"
              link
              size="small"
              @click.stop="addBtn(scope.row.data.id)"
            >
              <i-ep-plus />按钮
            </el-button>

            <el-button
              v-hasPerm="['sys:menu:edit']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(undefined, scope.row.data)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:menu:del']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.data.id)"
              ><i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      destroy-on-close
      append-to-body
      width="1000px"
      @close="closeDialog"
      top="5vh"
    >
      <el-form
        ref="menuFormRef"
        :model="formData"
        :rules="rules"
        label-width="160px"
      >
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="formData.pcode"
            placeholder="选择上级菜单"
            :data="menuOptions"
            filterable
            check-strictly
            node-key="id"
            :props="defaultProps"
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type" @change="onMenuTypeChange">
            <el-radio value="0">目录</el-radio>
            <el-radio value="1">菜单</el-radio>
            <el-radio value="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 权限标识 -->
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" placeholder="sys:user:add" />
        </el-form-item>

        <el-form-item
          v-if="
            formData.type == MenuTypeEnum.CATALOG ||
            formData.type == MenuTypeEnum.MENU
          "
          label="路由路径"
          prop="path"
        >
          <el-input
            v-if="formData.type == MenuTypeEnum.CATALOG"
            v-model="formData.path"
            placeholder="例如: /system"
          />
          <el-input v-else v-model="formData.path" placeholder="user" />
        </el-form-item>

        <el-form-item
          v-if="formData.type == MenuTypeEnum.CATALOG"
          label="跳转路径"
          prop="redirect"
        >
          <el-input
            v-model="formData.redirect"
            placeholder="子级例如: /dashboard"
          />
        </el-form-item>

        <!-- 组件页面完整路径 -->
        <el-form-item
          v-if="formData.type == MenuTypeEnum.MENU"
          label="页面路径"
          prop="component"
        >
          <el-input
            v-model="formData.component"
            placeholder="例如: system/user/index"
            style="width: 95%"
          >
            <template v-if="formData.type == MenuTypeEnum.MENU" #prepend
              >src/views/</template
            >
            <template v-if="formData.type == MenuTypeEnum.MENU" #append
              >.vue</template
            >
          </el-input>
        </el-form-item>

        <el-form-item
          v-if="formData.type !== MenuTypeEnum.BUTTON"
          prop="visible"
          label="显示状态"
        >
          <el-radio-group v-model="formData.hidden">
            <el-radio :value="false">显示</el-radio>
            <el-radio :value="true">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="formData.type === MenuTypeEnum.MENU"
          label="是否缓存"
        >
          <el-radio-group v-model="formData.cache">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.MENU" label="侧边栏">
          <el-radio-group v-model="formData.sideBar">
            <el-radio :value="true">有</el-radio>
            <el-radio :value="false">没有</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>

        <el-form-item
          v-if="formData.type !== MenuTypeEnum.BUTTON"
          label="图标"
          prop="icon"
        >
          <!-- 图标选择器 -->
          <icon-select v-model="formData.icon" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  // eslint-disable-next-line vue/no-reserved-component-names
  name: "Menu",
  inheritAttrs: false,
});

import { useUserStore } from "@/store/modules/user";
import { usePermissionStore } from "@/store/modules/permission";
import router from "@/router";
import { MenuQuery, MenuForm } from "@/api/menu/types";
import { listMenus, saveMenu, deleteMenu, createBtn } from "@/api/menu";

import { MenuTypeEnum } from "@/enums/MenuTypeEnum";

const queryFormRef = ref(ElForm);
const menuFormRef = ref(ElForm);
const tableRef = ref(null);

const defaultProps = {
  children: "children",
  label: "name",
};

const treeProps = {
  children: "children",
  hasChildren: "hasChildren",
};

const loading = ref(false);
const dialog = reactive({
  title: "",
  visible: false,
});

const queryParams = reactive<MenuQuery>({});
const menuList = ref<TreeResult<MenuForm>[]>([]);
const menuOptions = ref<TreeResult<MenuForm>[]>([]);

const formData = reactive<MenuForm>({
  pcode: "0",
  hidden: false,
  sort: 1,
  type: MenuTypeEnum.MENU,
  cache: false,
  icon: "",
  component: "",
  path: "",
  sideBar: true,
  redirect: "",
});

const rules = reactive({
  pcode: [{ required: true, message: "请选择顶级菜单", trigger: "blur" }],
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
  path: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
  component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  hidden: [{ required: true, message: "请选择是否缓存", trigger: "blur" }],
  code: [{ required: true, message: "权限标识不能为空", trigger: "blur" }],
});

// 选择表格的行菜单ID
const selectedRowMenuId = ref<string | undefined>();

const menuCacheData = reactive({
  type: "",
  path: "",
});

/**
 * 查询
 */
function handleQuery() {
  // 重置父组件
  loading.value = true;
  return listMenus(queryParams)
    .then(({ data }) => {
      menuList.value = data;
    })
    .then(() => {
      loading.value = false;
    });
}

/** 重新加载菜单 */
async function reloadMenu() {
  const userStore = useUserStore();
  const permissionStore = usePermissionStore();
  const { menuList } = await userStore.getUserInfo({ cache: false });
  const accessRoutes = await permissionStore.generateRoutes(menuList);
  accessRoutes.forEach((route) => {
    router.addRoute(route);
    location.reload();
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/**行点击事件 */
function onRowClick(row: MenuForm) {
  selectedRowMenuId.value = row.id;
}

/**自动生成菜单按钮 */
function addBtn(id: string) {
  createBtn(id).then(() => {
    handleQuery();
  });
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function openDialog(pcode?: string, data?: MenuForm) {
  if (!menuOptions.value.length) {
    menuOptions.value = [
      { id: "0", name: "顶级菜单", children: menuList.value },
    ];
  }
  dialog.visible = true;
  if (data) {
    dialog.title = "编辑菜单";
    Object.assign(formData, data);
    menuCacheData.type = data.type;
    menuCacheData.path = data.path ?? "";
  } else {
    dialog.title = "新增菜单";
    if (pcode === "0") {
      formData.type = MenuTypeEnum.CATALOG;
    }
    formData.pcode = pcode;
  }
}

/** 菜单类型切换事件处理 */
function onMenuTypeChange() {
  // 如果菜单类型改变，清空路由路径；未改变在切换后还原路由路径
  if (formData.type !== menuCacheData.type) {
    formData.path = "";
  } else {
    formData.path = menuCacheData.path;
  }
}

/** 菜单保存提交 */
function submitForm() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.id;
      saveMenu(formData).then(() => {
        if (menuId) {
          ElMessage.success("修改成功");
        } else {
          ElMessage.success("新增成功");
        }
        closeDialog();
        handleQuery();
      });
    }
  });
}

/** 删除菜单 */
function handleDelete(menuId: string) {
  if (!menuId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteMenu([menuId]).then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      });
    })
    .catch(() => ElMessage.info("已取消删除"));
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();

  formData.name = "";
  formData.id = undefined;
  formData.pcode = "0";
  formData.hidden = false;
  formData.sort = 1;
  formData.code = undefined;
  formData.component = undefined;
  formData.path = undefined;
  formData.cache = false;
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped lang="scss">
// :deep(.el-table__body-wrapper tr td.el-table-fixed-column--right) {
//   background: #17222f;
// }
</style>
